from core import get_page_from_request, get_parentpage_from_request
from django.http import HttpResponseRedirect, Http404
from pagemagic.core import get_page_from_path
from pagemagic.models import Page

class CascadeRedirectIf404Middleware:
    def process_exception(self, request, exception):
        if request.method == 'POST':
            return
        path = request.path
        if not path.endswith('/'):
            path += '/'
        if isinstance(exception, Http404) and len(path) > 1:
            return HttpResponseRedirect(path.rstrip('/').rsplit('/', 1)[0] + '/')

class LazyPagemagic:
    def __init__(self, request):
        self.request = request

    @property
    def allpages(self):
        if not hasattr(self, '_allpages'):
            self._allpages = Page.preload()
        return self._allpages

    @property
    def currentpage(self):
        if not hasattr(self, '_currentpage'):
            try:
                self._currentpage = get_page_from_request(self.request)
            except Http404:
                self._currentpage = None
        return self._currentpage

    @property
    def parentpage(self):
        if not hasattr(self, '_parentpage'):
            if self.currentpage:
                self._parentpage = self.currentpage.parent
            else:
                self._parentpage = get_parentpage_from_request(self.request)
        return self._parentpage

    def set_currentpage(self, path):
        self._currentpage = get_page_from_path(self.request, path)

    def set_parentpage(self, path):
        self._parentpage = get_page_from_path(self.request, path)


class MixPagemagicMiddleware:
    def process_request(self, request):
        request.pagemagic = LazyPagemagic(request)

